package com.infocollect.project.grant.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.infocollect.common.exception.CustomException;
import com.infocollect.common.utils.SecurityUtils;
import com.infocollect.common.utils.bean.BeanUtils;
import com.infocollect.common.utils.poi.JxExcelUtil;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.project.grant.domain.*;
import com.infocollect.project.grant.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.infocollect.framework.aspectj.lang.annotation.Log;
import com.infocollect.framework.aspectj.lang.enums.BusinessType;
import com.infocollect.framework.web.controller.BaseController;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.common.utils.poi.ExcelUtil;
import com.infocollect.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 报名信息Controller
 *
 * @author infocollect
 * @date 2022-05-21
 */
@RestController
@RequestMapping("/grant/examinergrant")
public class GrExaminerGrantController extends BaseController
{
    @Autowired
    private IGrExaminerGrantService grExaminerGrantService;
    @Autowired
    private IGrUserCompanyService userCompanyService;
    @Autowired
    private IGrCompanyService companyService;
    @Autowired
    private IGrGrantService grantService;
    @Autowired
    private IGrFamiliesService familiesService;

    /**
     * 查询报名信息列表
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:list')")
    @GetMapping("/list")
    public TableDataInfo list(GrExaminerGrantDto grExaminerGrantDto)
    {
        AjaxResult result = getUserCompanyIds(grExaminerGrantDto);
        if((Integer) result.get("code")!=200)
        {
            throw new CustomException((String)result.get("msg"),500);
        }
        startPage();
        grExaminerGrantDto.setUserCompanyIds((List<Long>)result.get("data"));
        List<GrExaminerGrantDto> list = grExaminerGrantService.selectGrExaminerGrantDtoList(grExaminerGrantDto);
        return getDataTable(list);
    }

    /**
     * 导出报名信息列表
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:export')")
    @Log(title = "报名信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GrExaminerGrantDto grExaminerGrantDto)
    {
        AjaxResult result = getUserCompanyIds(grExaminerGrantDto);
        if((Integer) result.get("code")!=200)
        {
            throw new CustomException((String)result.get("msg"),500);
        }
        grExaminerGrantDto.setUserCompanyIds((List<Long>)result.get("data"));
        List<GrExaminerGrantDto> list = grExaminerGrantService.selectGrExaminerGrantDtoList(grExaminerGrantDto);
        list.stream().forEach(grexaminerGrant ->{
            if("1".equals(grexaminerGrant.getSex())){
                grexaminerGrant.setSex("男");
            }
            if("0".equals(grexaminerGrant.getSex())){
                grexaminerGrant.setSex("女");
            }
            if("Y".equals(grexaminerGrant.getIsJoin())){
                grexaminerGrant.setIsJoin("是");
            }else{
                grexaminerGrant.setIsJoin("否");
            }
        });
        ExcelUtil<GrExaminerGrantDto> util = new ExcelUtil<GrExaminerGrantDto>(GrExaminerGrantDto.class);
        return util.exportExcel(list, "examinergrant");
    }
    /**
     * 导出报名信息列表
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:export')")
    @Log(title = "报名信息", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTeacher")
    public AjaxResult exportTeacher(GrExaminerGrantDto grExaminerGrantDto)
    {
        AjaxResult result = getUserCompanyIds(grExaminerGrantDto);
        if((Integer) result.get("code")!=200)
        {
            throw new CustomException((String)result.get("msg"),500);
        }
        grExaminerGrantDto.setUserCompanyIds((List<Long>)result.get("data"));
        List<TeacherGrExaminerGrantDto> list = grExaminerGrantService.selectTeacherGrExaminerGrantDtoList(grExaminerGrantDto);
        ExcelUtil<TeacherGrExaminerGrantDto> util = new ExcelUtil<TeacherGrExaminerGrantDto>(TeacherGrExaminerGrantDto.class);
        return util.exportExcel(list, "教师资格阅卷报名信息");
    }
    /**
     * 导出报名信息列表_考点
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:export')")
    @Log(title = "报名信息", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPoint")
    public AjaxResult exportPoint(GrExaminerGrantDto grExaminerGrantDto)
    {
        AjaxResult result = getUserCompanyIds(grExaminerGrantDto);
        if((Integer) result.get("code")!=200)
        {
            throw new CustomException((String)result.get("msg"),500);
        }
        grExaminerGrantDto.setUserCompanyIds((List<Long>)result.get("data"));
        List<PointGrExaminerGrantDto> list = grExaminerGrantService.selectPointGrExaminerGrantDtoList(grExaminerGrantDto);
        ExcelUtil<PointGrExaminerGrantDto> util = new ExcelUtil<>(PointGrExaminerGrantDto.class);
        return util.exportExcel(list, "教师资格阅卷报名信息_考点");
    }
    /**
     * 获取报名信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(grExaminerGrantService.selectGrExaminerGrantDtoById(id));
    }

    /**
     * 新增报名信息
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:add')")
    @Log(title = "报名信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GrExaminerGrantDto grExaminerGrant)
    {
        return grExaminerGrantService.insertGrExaminerGrantDto(grExaminerGrant);
    }

    /**
     * 修改报名信息
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:edit')")
    @Log(title = "报名信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GrExaminerGrantDto grExaminerGrant)
    {
        AjaxResult result = grExaminerGrantService.updateGrExaminerGrantDto(grExaminerGrant);
        return result;
    }

    /**
     * 删除报名信息
     */
    @PreAuthorize("@ss.hasPermi('grant:examinergrant:remove')")
    @Log(title = "报名信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(grExaminerGrantService.deleteGrExaminerGrantByIds(ids));
    }
    private AjaxResult getUserCompanyIds(GrExaminerGrantDto grExaminerGrantDto){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long grantId = grExaminerGrantDto.getGrantId();
        List<Long> userCompanyIds = new ArrayList<>();
        if(SecurityUtils.isInfocollectAdmin(userId)){
            //如果是管理员，不用做任何限制
            return AjaxResult.success(userCompanyIds);
        }
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setUserId(userId);
        userCompany.setGrantId(grantId);
        List<GrUserCompany> userCompanyList = userCompanyService.selectGrUserCompanyList(userCompany);
        if(userCompanyList.size()<=0){
            return AjaxResult.error("没有找到派出单位相关数据");
        }
        userCompany = userCompanyList.get(0);
        Long userCompanyId = userCompany.getCompanyId();
        GrCompany company = companyService.selectGrCompanyById(userCompanyId);
        if(company==null){
            return AjaxResult.error("没有找到派出单位相关数据");
        }

        if(2==company.getLvl()){
            Long parentId = company.getId();
            company = new GrCompany();
            company.setParentId(parentId);
            company.setGrantId(grantId);
            List<GrCompany> companyList = companyService.selectGrCompanyList(company);
            userCompanyIds= companyList.stream().map(tmp->{return tmp.getId();}).collect(Collectors.toList());
        }else{
            userCompanyIds.add(company.getId());
        }
        //为了防止没有任何用户，默认加个0
        userCompanyIds.add(0l);
        return AjaxResult.success(userCompanyIds);
    }

    @Log(title = "考官管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Long grantId,Long companyId) throws Exception
    {
        if(grantId==null || companyId ==null){
            return AjaxResult.error("上传错误，请选择项目或派出单位！");
        }
        GrCompany company = companyService.selectGrCompanyById(companyId);
        if(company==null){
            return AjaxResult.error("没有找到派出单位相关数据");
        }
        if(3!=company.getLvl()){
            return AjaxResult.error("数据只能导入到第三级派出单位");
        }
        Integer dataNumber = 0;
        if(file!=null)
        {
            List<GrFamilies> familiesList= getFamiliesListForGrantId(grantId);
            ExcelUtil<GrExaminerGrantImportDto> util = new ExcelUtil<>(GrExaminerGrantImportDto.class);
            List<GrExaminerGrantImportDto> xsbBeanList = util.importExcel(file.getInputStream());
            List<GrExaminerGrantImportDto> list1 = new ArrayList<>();
            for(int ni =xsbBeanList.size()-1; ni>=0;ni-- )
            {
                GrExaminerGrantImportDto record = xsbBeanList.get(ni);
                if(StringUtils.isEmpty(record.getIdcard()))
                {
                    xsbBeanList.remove(ni);
                    record.setFailerReason("身份证号为空");
                    list1.add(record);
                    continue;
                }
                Long familiesId= getFamiliesIdForName(familiesList,record.getTypeName());
                record.setType(familiesId);
                Long subjectId= getFamiliesIdForName(familiesList,record.getSubjectCodeName());
                record.setSubjectCode(subjectId);
                if(familiesId==0|| subjectId==0){
                    record.setFailerReason("科类或学科名称错误");
                    list1.add(record);
                    continue;
                }
                GrExaminerGrantDto grExaminerGrantDto = new GrExaminerGrantDto();
                BeanUtils.copyProperties(record,grExaminerGrantDto);
                grExaminerGrantDto.setIsImport("1");
                String sex = grExaminerGrantDto.getSex();
                if("男".equals(sex)){
                    grExaminerGrantDto.setSex("1");
                }else if("女".equals(sex)){
                    grExaminerGrantDto.setSex("1");
                 }else {
                    record.setFailerReason("性别错误");
                    list1.add(record);
                    continue;
                }
                String isJoin = grExaminerGrantDto.getIsJoin();
                if("是".equals(isJoin)){
                    grExaminerGrantDto.setIsJoin("Y");
                }else {
                    grExaminerGrantDto.setIsJoin("N");
                }
                grExaminerGrantDto.setCompanyId(companyId);
                grExaminerGrantDto.setGrantId(grantId);
                AjaxResult result = grExaminerGrantService.insertGrExaminerGrantDto(grExaminerGrantDto);
                if((int)result.get("code")!=200){
                    String msg = (String)result.get("msg");
                    record.setFailerReason(msg);
                    list1.add(record);
                }
            }

            dataNumber = dataNumber + xsbBeanList.size();

//            List<SceneListForPointExcel> list1 = grExaminerSceneService.sceneListForPointExcelUpload(xsbBeanList,grantId,sceneId,examinerPointId);


            if (list1 != null && list1.size()>0){
                return AjaxResult.success("数据导入成功"+(dataNumber-list1.size())+"条，失败"+list1.size()+"条，具体请查看excel清单",list1);
            }
        }
        return AjaxResult.success("数据全部导入成功,导入成功数量:"+dataNumber+"条");
    }
    //expTemplate
    @GetMapping(value = "/expTemplate")
    public AjaxResult downloadExcelFile(HttpServletResponse response) throws IOException {
        List<GrExaminerGrantImportDto> list = new ArrayList<>();
        ExcelUtil<GrExaminerGrantImportDto> util = new ExcelUtil<>(GrExaminerGrantImportDto.class);
        return util.exportExcel(list, "人员导入模板");
    }
    private List<GrFamilies> getFamiliesListForGrantId(Long grantId){
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();
        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        return familiesList;
    }
    private Long getFamiliesIdForName(List<GrFamilies> familiesList, String familiesName){
        Long familiesId = 0l;
        for(int row=0;row<familiesList.size();row++){
            GrFamilies families = familiesList.get(row);
            if(familiesName.equals(families.getFamiliesName())){
                familiesId = families.getId();
                break;
            }
        }
        if(familiesId==0){
            for(int row=0;row<familiesList.size();row++){
                GrFamilies families = familiesList.get(row);
                if(familiesName.equals(families.getFamiliesCode())){
                    familiesId = families.getId();
                    break;
                }
            }
        }
        return familiesId;
    }
}
